package com.gosling.cloudspace.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.gosling.cloudspace.common.annotation.JwtIgnore;
import com.gosling.cloudspace.tools.IOTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @email 1793327033@qq.com
 * @classname SysLoginController
 * @author: osc_lihonglin
 * @date: 2021/6/29 20:13
 */
@JwtIgnore
@CrossOrigin
@Controller
public class CaptchaController {

    @Autowired
    private Producer kaptchaProducer;

    /**
     * 获取图形验证码
     *
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @CacheEvict(allEntries = true)
    @JwtIgnore
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = kaptchaProducer.createText();
        //生成图片验证码
        BufferedImage image = kaptchaProducer.createImage(text);
        //保存到shiro session
        HttpSession session = request.getSession();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOTool.closeQuietly(out);
    }

}